'''
Get the historic daily data of the S&P 500 stocks.
Each row include Date, Open, High, Low, Close, Volume, Adj Close

Created on April, 2012
@author: bruce
'''

from src.util.logutil import LogFile
from src.util.datacollectutil import YahooFinance

class HistQuotes:    
    def __init__(self, symbols_file, output_dir="output\\"):
        # If output_dir is not provided, we will use the local test directory.                         
        self.__output_dir   = output_dir 
        self.__symbols_path =  "input\\" + symbols_file 
        self.__log = LogFile("hist quotes log")   
        self.__log.detail_log('Normal', 'Start of hist quotes!')    
        self.__get_symbols()  
        
        self._stockquotes = YahooFinance()                 
    
    """
    Get the S&P 500 symbols from the input file.
    """
    def __get_symbols(self):             
        symbol_file = open(self.__symbols_path, 'r')
        self.__symbols = symbol_file.read().split()
    
    """
    Output the historical daily data to the symbol file.
    """
    def __output_symbolfile(self, symbol, content):
        lines = content.split('\n')        
        symbol_file = open(self.__output_dir + symbol + ".csv", 'w')
        symbol_file.write(lines[0] + "\n")
        del lines[0]
        lines.reverse()
        for line in lines:
            if line != '':
                symbol_file.write(line + "\n") 
        symbol_file.close()                
            
    """
    Get the historical quotes of the symbol and output the data to the symbol file.
    """         
    def _get_histquotes(self, symbol):
        symbol_quotes = self._stockquotes.gethistquotes(symbol)
        if len(symbol_quotes) != 0:  # empty quote string means we failed in the http request.
            self.__output_symbolfile(symbol, symbol_quotes)
        else:
            self.__log.detail_log('Error', 'Unrecorded symbol:\t' +  symbol)

    def run(self):
        for symbol in self.__symbols:
            self._get_histquotes(symbol)        
        self.__log.closelog()
        self._stockquotes.uninitialize()
        
if __name__ == "__main__":      
    # Test
    test_symbols_file = "test_symbols.list"   
    sp500_hist = HistQuotes(test_symbols_file)      
    sp500_hist.run()
    